Abstract with interface usage

  • Note

    we can use abstract class and interface together

    When to Use Both Abstract Class and Interface Together

    You need to allow multiple inheritance of behavior (via interfaces), but also want to share default behavior

    we use this pattern to build libraries and frameworks

    
    
    interface LoggerInterface {
        public function log(string $message);
    }
    
    interface FileWritable {
        public function writeToFile(string $filename);
    }
    
    abstract class LoggerBase implements LoggerInterface {
        // Shared property
        protected string $logLevel = 'INFO';
    
        // Concrete method
        public function setLogLevel(string $level) {
            $this->logLevel = $level;
        }
    
        // Abstract method from LoggerInterface
        abstract public function log(string $message);
    }
    
    // Concrete class that uses both abstract class and interface
    class FileLogger extends LoggerBase implements FileWritable {
    
        public function log(string $message) {
            echo "[{$this->logLevel}] $message\n";
        }
    
        public function writeToFile(string $filename) {
            file_put_contents($filename, "[{$this->logLevel}] Logging to file\n", FILE_APPEND);
        }
    }
    
    // Usage
    $logger = new FileLogger();
    $logger->setLogLevel('DEBUG');
    $logger->log("This is a debug message.");
    $logger->writeToFile("log.txt");